package com.farata.android.samples;

import java.util.ArrayList;

import clear.services.ClearDataService;
import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;
import air.VoiceRecognitionFlex.AppEntry;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;

public class FlexHelperActivity extends AppEntry {
    /** Called when the activity is first created. */
	
	public static FlexHelperActivity instance;

	public FlexHelperActivity() {
		super();
		instance = this;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent clearDataServiceIntent = new Intent(this, ClearDataService.class);
        startService(clearDataServiceIntent);
    }
    
    // This method gets called from RemoteObject, effectively - from Flex
	public void recognizeVoice(int requestCode, String prompt) {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
		startActivityForResult(intent, requestCode);
	}
	
	// This method pushes the result of the voice recognition back to Consumer in the
	// Flex application
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 12345 && resultCode == RESULT_OK) {
			// Fill the list view with the strings the recognizer thought it
			// could have heard
			ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

			MessageBroker msgBroker = MessageBroker.getMessageBroker(null);
			AsyncMessage msg = new AsyncMessage();

			msg.setDestination("voiceRecognition");
			msg.setClientId(UUIDUtils.createUUID(true));
			msg.setMessageId(UUIDUtils.createUUID(true));
			msg.setTimestamp(System.currentTimeMillis());
			msg.setBody(matches);
			msgBroker.routeMessageToService(msg, null);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}